import { request } from '../../utils/request'
import { request_netEase } from '../../utils/request_netEase'
let that
const listGroupData = [
  {
  id:3102,
  name:"二次元",
  active:'active'
}
,{
  id:2103,
  name:"游戏"
},
{
  id:3109,
  name:"街舞"
},
{
  id:4108,
  name:"动漫"
},
{
  id:11107,
  name:"火影忍者"
},
{
  id:12144,
  name:"名侦探柯南"
}
,{
  id:60100,
  name:"翻唱"
},
{
  id:264120,
  name:"热歌看得见"
},
{
  id:243125,
  name:"#歌手#"
},
{
  id:1103,
  name:"萌宠"
}
]
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //读取所有标签数据加载太慢了, 改为只请求选择的数据,
    //原因找到了, 是清除缓存, 没有cookie, 导致请求拿不到数据

/*
     不需要缓存所有视频数据了, 加载时间大大减少
    videoNavList:[], 
*/
    selectVideos:[],
    selectId:3102,
    listGroup:listGroupData,
    videoLast:{
      id:0,
      videoContext:{},
      // status:''
    },
    videoTime:[],
    //控制下拉刷新是否结束
    isRefresh:false,
    //控制上拉加载的分页
    offset:0,
    //控制上拉加载刷新后的滚动条位置
    initialScroll:0.1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    that = getCurrentPages()[0]
    that.getInitialVideos()
  },
  toSearch: () => {
    wx.navigateTo({
      url:'/pages/search/search'
    })
  },
  changeActive: (e) => {
    that.setData({
      selectVideos:[]
    })
    wx.showLoading({
      title:'加载中'
    })
    //为了实现scroll-view的scroll-into-view功能, id修改为`group${id}`, 现在的id为dataset里面的id
    const { groupid:id } = e.target.dataset
    //这里拿到的id是String类型
    // const { listGroup, videoNavList } = that.data
    //item.id是Number类型
    //Array.PhotoType.map()当元素为引用类型时, 会修改原数组.
    //一开始都是使用的item => if(item.id == id){item.active = 'active}这种方式, 发现litGroup变为空数组
    //或者不会改变listGroup的值
    that.changeDataById(id)
  },
  changeDataById: async (id_string, offset =0) => {
    const id = (id_string>>>0)
    const { selectId } = that.data
    id !== selectId?that.setData({
      selectId:id,
      offset:0
    }):null
    //这里的id参数已经转化为Number类型
    const { listGroup } = that.data
    const newListGroup = listGroup.map(item => 
      (item.id === id)?{...item, active:'active'}:{...item, active:''}
    )
    // const selectGroup = videoNavList.find(item => item.id === id)
    // const selectVideos = selectGroup.videos
    const selectGroup = await request_netEase(`getVideosByGroup/${id}/${offset}`)
    const selectVideos = selectGroup.videos
    that.setData({
      listGroup:newListGroup,
      selectVideos
    })
    wx.hideLoading()
  },
//   getInitialVideos: () => {
//     const { selectId:id } = that.data
//     request('video/group', {id}).then(
//       res => {
//         let selectVideos = []
//         res.datas.forEach(({data}) => {
//           const { coverUrl, vid, title } = data
//           //根据vid拿到视频url
//           return request('video/url', {id:vid}).then(res => {
//             const { urls } = res
//             const { url } = urls[0]
//             selectVideos.push({
//               coverUrl,
//               title,
//               url,
//               vid
//             })
//           })
//         })
//         that.setData({
//           selectVideos
//         })
//         console.log(that.data.selectVideos)
//   })
// },
  getInitialVideos: () => {
    const { selectId } = that.data
    that.changeDataById(selectId)
    //根据listGroup列表里的元素id获取标签id对应的视频list
    //不需要下列代码了, 首次只获取selectId的视频, 不再全部获取, 减少初次加载时间
/*     listGroup.map(async group =>{
      const { id } = group
      const groupVideos = await request_netEase(`getVideosByGroup/${id}`)
      videoListData.push(groupVideos)
      if(id === selectId) {
        that.setData({
          selectVideos:groupVideos.videos
        })
      }
      if(listGroup.length === videoListData.length) that.setData({
        videoNavList:videoListData
      }) */

/*    以下代码逻辑已经在后端实现， 不需要重复处理   
      const { id, name } = group
      //对于每个group(标签), 初始化videos数组为空
      
      //根据标签id拿到视频列表数组, 数组中有视频vid
      request('video/group', {id}).then(
        res => {
          let videos = []
          res.datas.forEach(({data}) => {
            const { coverUrl, vid, title } = data
            //根据vid拿到视频url
            return request('video/url', {id:vid}).then(res => {
              const { urls } = res
              const { url } = urls[0]
              videos.push({
                coverUrl,
                title,
                url,
                vid
              })
            })
          })
          videoListData.push({
            id,
            name,
            videos
          })
        }) */
        // })
        // that.setData({
        //   videoNavList:videoListData
        // })
  },
  handlePlay: e => {
    const { videoLast, videoTime } = that.data
    const { id:lastId, videoContext:videoContextLast } = videoLast
    const { id } = e.target
    //看视频是否之前播放过
    const videoIndex = videoTime.findIndex(video => video.vid === id)
    let time
    if(videoIndex !== -1){
      const { currentTime } = videoTime[videoIndex]
      time = currentTime
    }
    else time = 0
    
    // const status = (
    //   (oldStatus === ''|| oldStatus === 'pause')?'play':'pause'
    //  )
    //不是同一个视频或者为第一个视频, 用video组件的autoplay属性也可以实现
    if(lastId !== id){
      // videoContext不为空, 那么暂停上一个视频
      videoContextLast.constructor !== Object && videoContextLast.pause()
      const videoContext = wx.createVideoContext(id)
      videoContext.seek(time)
      videoContext.play()
      return that.setData({
        videoLast:{
          id,
          videoContext,
          // status
      }
    })
    }
    //同一个视频的情况下, 貌似不需要判断, video的播放和暂停可以有效的执行
    //所以去掉status部分的data
  /*     
    如果是同一个视频, 应该改变视频状态
        ————如果暂停那么应该变为继续播放,
        ————如果播放那么应该改为暂停 
    */
  //  else{
  //   oldStatus === 'pause' && videoContextLast.play()
  //   oldStatus === 'play' && videoContextLast.pause()
  //   console.log(`此次点击了${status}, 视频id为${id}, 上次的id为${lastId}`)
  //   return that.setData({
  //     videoLast:{
  //       ...videoLast,
  //       status
  //     }
  //   })
  //  }
  },
  getTime: e => {
    //获取播放的视频vid
    const { id:vid } = e.target
    const { currentTime } = e.detail
    const { videoTime } = that.data
    // const videoTime = videoTimeOld.slice()
    //没有播放过视频
    const videoIndex = videoTime.findIndex(item => item.vid === vid)
    if(videoIndex === -1){
      videoTime.push({
        vid,
        currentTime
      })
    }
    else videoTime[videoIndex] = {
      ...videoTime[videoIndex],
      currentTime
    }
    that.setData({
      videoTime
    })
  },
  // handlePulling: e => {
  //   console.log(e, 'pulling')
  // },
  handleRefresh: e => {
    const { selectId } = that.data
    that.changeDataById(selectId)
    that.setData({
      isRefresh:false,
      offset:0
    })
  },
  handleLower:() => {
    const { selectId, offset:oldOffset } = that.data
    wx.showLoading({
      title:'上拉加载中'
    })
    //先增加offset再changeData不然会老数据更新2次, 导致第一次看起来没有上拉加载
    const offset = oldOffset +1
    that.changeDataById(selectId, offset)
    //这边会有一些bug, 上拉有时候会不更新
    that.setData({
      offset,
      initialScroll:0.01
    })
  },
  // handleRestore: e => {
  //   console.log(e, 'restore')
  // }, 
  // handleAbort: e => {
  //   console.log(e, 'abort')
  // },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    console.log('页面下拉刷新')
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  // onReachBottom() {

  // },

  /**
   * 用户点击右上角分享
   * promise返回值定义title, path, 和图片
   * promise
   */
  onShareAppMessage({from}) {
    console.log(from)
    return {
      title:'JOJO云音乐1',
      path:'/pages/video/video',
      promise:new Promise((resolve, reject) => {
        resolve({
          title:'JOJO云音乐2',
          path:'/pages/personal/personal'
        })
      } )
    }
  }
})